package com.kmproject.haifu.mvp.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.irozon.library.HideKey;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.di.component.DaggerHomeMainComponent;
import com.kmproject.haifu.mvp.contract.HomeMainContract;
import com.kmproject.haifu.mvp.model.entity.beans.HomeBannerBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.SeletCityBean;
import com.kmproject.haifu.mvp.model.entity.resbean.HFLocationBean;
import com.kmproject.haifu.mvp.presenter.HomeMainPresenter;
import com.kmproject.haifu.mvp.ui.activity.SecondHandListShowActivity;
import com.kmproject.haifu.mvp.ui.activity.WebViewActivity;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.adapter.FragmentTitlesAdapter;
import com.kmproject.haifu.mvp.ui.adapter.HouseRentingShowMainItemAdapter;
import com.kmproject.haifu.mvp.ui.holder.HomeBannerViewHolder;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.MyTextWatcher;
import com.kmproject.haifu.mvp.ui.widget.NoScrollViewPager;
import com.kmproject.haifu.mvp.ui.widget.ScaleTransitionPagerTitleView;
import com.xw.repo.XEditText;
import com.zhouwei.mzbanner.MZBannerView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/08/2019 23:52
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HomeMainFragment extends BaseFragment<HomeMainPresenter> implements HomeMainContract.View, TextView.OnEditorActionListener, View.OnKeyListener {
    @BindView(R.id.inclue_search_title_address)
    TextView inclueSearchTitleAddress;
    @BindView(R.id.inclue_search_title_search_lay)
    LinearLayout inclueSearchTitleSearchLay;
    @BindView(R.id.inclue_search_title_lay)
    LinearLayout inclueSearchTitleLay;
    @BindView(R.id.search_title_ts)
    TextView searchTitleTs;

    @BindView(R.id.ll_root_view)
    LinearLayout ll_root_view;
    @BindView(R.id.banner_view)
    MZBannerView banner_view;
    @BindView(R.id.rv_home_main_category)
    RecyclerView rv_home_main_category;
    @BindView(R.id.wv_chat)
    WebView wv_chat;
    @BindView(R.id.mi_home_news_tab)
    MagicIndicator mi_home_news_tab;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;

    Unbinder unbinder;
    private HFLocationBean mbdLocation;
    private List<SeletCityBean> mSelectCityBeans;

    private List<String> titles;

    public static HomeMainFragment newInstance() {
        HomeMainFragment fragment = new HomeMainFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHomeMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_main, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        banner_view.setDelayedTime(3000);
        HideKey.initialize(getActivity());

        rv_home_main_category.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rv_home_main_category.setAdapter(new HouseRentingShowMainItemAdapter(mPresenter.getDatas()));

        titles = Arrays.asList(getResources().getStringArray(R.array.home_news_tab_title));
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(HomeNewsFragment.newInstance(0));
        fragments.add(HomeNewsFragment.newInstance(1));

        viewpager.setAdapter(new FragmentTitlesAdapter(getFragmentManager(), getActivity(), titles, fragments));
        viewpager.setCurrentItem(0);
        CommonNavigator commonNavigator = new CommonNavigator(getContext());
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(titles.get(index));
//                simplePagerTitleView.setWidth((ScreenUtils.getScreenWidth() - 30) / 3);
                simplePagerTitleView.setWidth(ScreenUtils.getScreenWidth() / 6);
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_191919));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_191919));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.END;
//                layoutParams.setMargins(0, 0, 0, 0);//4个参数按顺序分别是左上右下
                simplePagerTitleView.setLayoutParams(layoutParams);
                simplePagerTitleView.setOnClickListener(v -> {
                    mi_home_news_tab.onPageSelected(index);
                    commonNavigator.getAdapter().notifyDataSetChanged();
                    viewpager.setCurrentItem(index);
                });

                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setLineHeight(6.0f);
                linePagerIndicator.setColors(ArmsUtils.getColor(getContext(), R.color.color_F9D35A));

                return linePagerIndicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

        });

        mi_home_news_tab.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mi_home_news_tab, viewpager);

        if (DataHelper.getBooleanSF(getActivity(), AppConstant.user_isFirst_login)) {
            mPresenter.showPopuWindowToSearch(getActivity(), ll_root_view);
        }
        mPresenter.getIndexHouseArea();
        startLocation(false);
        initWebView();
        wv_chat.loadUrl("https://devtest.haifu365.com/nc/charts/");
        mPresenter.getHomeBanner();
    }

    private void setBannerView(List<HomeBannerBean> bannerBeans) {
        banner_view.setBannerPageClickListener((view, i) -> {
            Intent intent = new Intent(getContext(), WebViewActivity.class);
            intent.putExtra("title", "海服活动");
            intent.putExtra("url", bannerBeans.get(i).getLink());
//                intent.putExtra("url", "https://www.baidu.com/");
            ArmsUtils.startActivity(intent);
        });
        banner_view.setPages(bannerBeans, HomeBannerViewHolder::new);
        banner_view.start();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = wv_chat.getSettings();
        settings.setJavaScriptEnabled(true);//支持js
        settings.setUseWideViewPort(true);//将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setSupportZoom(true);//支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(false);//设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); //支持内容重新布局
        settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);   //开启 database storage API 功能
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        settings.setAppCacheMaxSize((5 * 1024 * 1024)); // 5MB
        settings.setGeolocationEnabled(true);//启用地理定位
//        //设置定位的数据库路径
//        val dir = context.applicationContext.getDir("database", Context.MODE_PRIVATE).path
//        settings.setGeolocationDatabasePath(dir)
        if (NetworkUtils.isConnected()) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }
    }

    private View searchHistoryView;
    private CustomPopWindow mCustomPopWindow4SearchHistory;
    private TextView tv_down_text;
    private ImageView imv_down_icon;
    private XEditText et_keyword;
    private TextView tv_clear_all;
    private TextView tv_cancel;
    private LinearLayout ll_top_search_input_layout;
    private RecyclerView rv_rent_seeking_search_history;
    private BaseRecyclerAdapter<String> searchHistoryAdapter;

    private String mKeyWord;

    private void showSearchHistoryView() {
        if (mCustomPopWindow4SearchHistory == null) {
            searchHistoryView = LayoutInflater.from(getContext()).inflate(R.layout.v_home_search_history, null);
            rv_rent_seeking_search_history = searchHistoryView.findViewById(R.id.rv_rent_seeking_search_history);
            ll_top_search_input_layout = searchHistoryView.findViewById(R.id.ll_top_search_input_layout);
            tv_down_text = searchHistoryView.findViewById(R.id.tv_down_text);
            imv_down_icon = searchHistoryView.findViewById(R.id.imv_down_icon);
            et_keyword = searchHistoryView.findViewById(R.id.et_keyword);
            tv_clear_all = searchHistoryView.findViewById(R.id.tv_clear_all);
            tv_cancel = searchHistoryView.findViewById(R.id.tv_cancel);
            rv_rent_seeking_search_history.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                    setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(false).build());
            ArmsUtils.configRecyclerView(rv_rent_seeking_search_history, new LinearLayoutManager(getContext()));
            rv_rent_seeking_search_history.setItemAnimator(new DefaultItemAnimator());

            searchHistoryAdapter = new BaseRecyclerAdapter<String>(R.layout.item_rent_seeking_search_history) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, String model, int position) {
                    holder.text(R.id.tv_record_text, model);
                }
            }.setOnItemClickListener((parent, view, position, id) -> {
                mKeyWord = (String) searchHistoryAdapter.getItem(searchHistoryAdapter.getRealItemPosition(position));
                dismissHistoryPw();
            });

            rv_rent_seeking_search_history.setAdapter(searchHistoryAdapter);

            tv_down_text.setOnClickListener(v -> showLeftPopupWindow(getActivity(), ll_top_search_input_layout));
            imv_down_icon.setOnClickListener(v -> showLeftPopupWindow(getActivity(), ll_top_search_input_layout));
            tv_clear_all.setOnClickListener(v -> {
                clearSearchHistory();
                showMessage(getString(R.string.success));
            });
            tv_cancel.setOnClickListener(v -> {
                if (StringUtils.isEmpty(et_keyword.getTextEx())) {
                    mKeyWord = "";
                    dismissHistoryPw();// 输入框为空时，显示取消
                } else {
                    mKeyWord = et_keyword.getTextEx();
                    addSearchHistory(mKeyWord);
                    goToSearchResultPage();
                }
                KeyboardUtils.hideSoftInput(et_keyword);
//                dismissHistoryPw();
            });
            et_keyword.setOnEditorActionListener(this);
            et_keyword.setOnKeyListener(this);
            et_keyword.addTextChangedListener(new MyTextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                    if (StringUtils.isEmpty(s)) {
                        mKeyWord = "";
                        tv_cancel.setText(getString(R.string.cancel));
                        tv_cancel.setTextColor(ContextCompat.getColor(getContext(), R.color.color_191919));
                    } else {
                        mKeyWord = et_keyword.getTextEx();
                        tv_cancel.setText(getString(R.string.search));
                        tv_cancel.setTextColor(ContextCompat.getColor(getContext(), R.color.textColor_alert_button_others));
                    }
                }
            });

            mCustomPopWindow4SearchHistory = initDropDownMenu(searchHistoryView, ViewGroup.LayoutParams.MATCH_PARENT);
        } else {
            mCustomPopWindow4SearchHistory.showAsDropDown(inclueSearchTitleLay, 0, 0);
        }
        getSearchHistory();
    }

    private CustomPopWindow initDropDownMenu(View contentView, int height) {
        ViewGroup parentViewGroup = (ViewGroup) contentView.getParent();
        if (parentViewGroup != null) {
            parentViewGroup.removeAllViews();
        }
        //创建并显示popWindow
        CustomPopWindow mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, height)
                .setAnimationStyle(R.style.popupWindowAnimationScale)
                .enableBackgroundDark(false) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .create();
        mCustomPopWindow.getPopupWindow().setOnDismissListener(() -> {
            // todo 处理弹窗隐藏后的一些事宜
//            if (StringUtils.isEmpty(mKeyWord)) {
//
//            } else {
//
//            }
        });
        mCustomPopWindow.showAsDropDown(inclueSearchTitleLay, 0, 0);

//        vHalfWhiteLayout.setVisibility(View.VISIBLE);
        return mCustomPopWindow;
    }

    private List<String> searchHistory;

    private void getSearchHistory() {
        if (searchHistory == null) {
            searchHistory = new ArrayList<>();
        }
        List<String> sh = DataHelper.getDeviceData(getContext(), search_tpe);
        searchHistory.clear();
        if (sh != null) {
            searchHistory.addAll(sh);
        }
        searchHistoryAdapter.refresh(searchHistory);
    }

    private void addSearchHistory(String searchKey) {
        searchHistory.add(0, searchKey);
        searchHistoryAdapter.refresh(searchHistory);
        DataHelper.saveDeviceData(getContext(), search_tpe, searchHistory);
    }

    private void clearSearchHistory() {
        if (searchHistory==null)
        {
            showMessage("没有可清除的内容");
            return;
        }
        searchHistory.clear();
        searchHistoryAdapter.refresh(searchHistory);
        DataHelper.removeSF(getContext(), search_tpe);
        searchHistory = null;
    }

    private void dismissHistoryPw() {
        if (mCustomPopWindow4SearchHistory != null) {
            mCustomPopWindow4SearchHistory.dissmiss();
        }
    }

    private CustomPopupWindow menuPopupWindow;
    private final String RENTING_HOUSE = "rentingHouse";//租房
    private final String SECOND_HAND_ITEM = "secondHandItem";//二手物品
    private String search_tpe = RENTING_HOUSE;

    /**
     * 左边菜单栏弹框
     *
     * @param activity
     * @param view
     */
    public void showLeftPopupWindow(Activity activity, View view) {
        menuPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.home_search_menu_popup_window)).parentView(view)
                .animationStyle(R.style.Animation_Activity).customListener(contentView -> {
                    TextView tv_menu_1 = contentView.findViewById(R.id.tv_menu_1);
                    TextView tv_menu_2 = contentView.findViewById(R.id.tv_menu_2);
                    tv_menu_1.setOnClickListener(v -> {
                        if (!search_tpe.equals(RENTING_HOUSE)) {
                            search_tpe = RENTING_HOUSE;
                            getSearchHistory();
                        }
                        tv_down_text.setText("租房");
                        menuPopupWindow.dismiss();
                    });
                    tv_menu_2.setOnClickListener(v -> {
                        if (!search_tpe.equals(SECOND_HAND_ITEM)) {
                            search_tpe = SECOND_HAND_ITEM;
                            getSearchHistory();
                        }
                        tv_down_text.setText("二手物品");
                        menuPopupWindow.dismiss();
                    });
                }).isHaveBackGround(false).isWrap(true).isMenu(true).build();
        menuPopupWindow.show();

    }

    @Override
    public void onResume() {
        super.onResume();
        banner_view.start();
        wv_chat.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        banner_view.pause();
        wv_chat.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (wv_chat != null) {
            wv_chat.clearHistory();
//            (web_view.getParent()).removeView(web_view)
            wv_chat.loadUrl("about:blank");
            wv_chat.stopLoading();
            wv_chat.destroy();
        }
    }

    /**
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.inclue_search_title_address, R.id.inclue_search_title_search_lay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.inclue_search_title_address:
                //地址筛选
                if (mPresenter.getCustomPopupWindow() == null) {
                    mPresenter.showPopuWindowToSearch(getActivity(), ll_root_view);
                } else {
                    mPresenter.getCustomPopupWindow().show();
                }

                if (mSelectCityBeans == null) {
                    mPresenter.getIndexHouseArea();
                }
                mPresenter.refershDatas(mSelectCityBeans);
                break;
            case R.id.inclue_search_title_search_lay:
                showSearchHistoryView();
                break;
        }
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void reciverLocation(HFLocationBean bdLocation) {
        showMessage("获取到定位信息了");
        mbdLocation = bdLocation;
        mPresenter.setLocation(mbdLocation);

    }

    @Override
    public void selectCitySuccess(HousePayWayBean housePayWayBean) {
        DataHelper.saveDeviceData(getActivity(), AppConstant.user_default_select_area, housePayWayBean);
        inclueSearchTitleAddress.setText(housePayWayBean.getName());
    }

    @Override
    public void getIndexHouseAreaSuccess(List<SeletCityBean> seletCityBeans) {
        mSelectCityBeans = seletCityBeans;
        mPresenter.refershDatas(seletCityBeans);
    }

    @Override
    public void startLocation(boolean isRefersh) {
        LocationManager locationManager = (LocationManager) Objects.requireNonNull(getActivity()).getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        // Criteria是一组筛选条件
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //设置定位精准度
        criteria.setAltitudeRequired(false);////设置是否可以定位海拔,如果设置定位海拔，返回一定是gps
        //是否要求海拔
        criteria.setBearingRequired(true);
        //是否要求方向
        criteria.setCostAllowed(true);
        //是否要求收费
        criteria.setSpeedRequired(true);
        //是否要求速度
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        //设置电池耗电要求
        criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
        //设置方向精确度
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
        //设置速度精确度
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        //设置水平方向精确度
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
        //设置垂直方向精确度
        if (ActivityCompat.checkSelfPermission(Objects.requireNonNull(getContext()), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Objects.requireNonNull(getContext()), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // todo 提示授权
            return;
        }
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null) {
            mbdLocation = new HFLocationBean(location);
            mPresenter.setLocation(mbdLocation);
            if (isRefersh) {
                showMessage("定位刷新成功");
            }
        }
    }

    @Override
    public void getHomeBannerSuccess(List<HomeBannerBean> bannerBeans) {
        if (bannerBeans != null && !bannerBeans.isEmpty()) {
            banner_view.setVisibility(View.VISIBLE);
            setBannerView(bannerBeans);
        } else {
            banner_view.pause();
            banner_view.setVisibility(View.GONE);
        }
    }

    private void goToSearchResultPage() {
        if (search_tpe==SECOND_HAND_ITEM)
        {
            //二手房
            //跳转到搜索界面
            Intent intent =new Intent(getActivity(), SecondHandListShowActivity.class);
            intent.putExtra("searchContent",et_keyword.getText().toString());
            ArmsUtils.startActivity(intent);
        }else {
            //房源

        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // 搜索
            if (!StringUtils.isTrimEmpty(mKeyWord)) {
                KeyboardUtils.hideSoftInput(et_keyword);
                addSearchHistory(mKeyWord);
//                dismissHistoryPw();
                goToSearchResultPage();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
            case EditorInfo.IME_ACTION_DONE:
            case EditorInfo.IME_ACTION_GO:
            case EditorInfo.IME_ACTION_NEXT:
            case EditorInfo.IME_ACTION_SEND: {
                // 搜索
                if (!StringUtils.isTrimEmpty(mKeyWord)) {
                    KeyboardUtils.hideSoftInput(et_keyword);
                    addSearchHistory(mKeyWord);
//                    dismissHistoryPw();
                    goToSearchResultPage();
                }
                return true;
            }
        }
        return false;
    }
}
